import sys
import threading
import time

from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse, JSONResponse
import webview
from starlette.middleware.cors import CORSMiddleware

from api import Api
import uvicorn
from pathlib import Path
import shutil

from script import *
from models import *

from database import Base, engine, get_db

Base.metadata.create_all(bind=engine)

currentTool = None
window_run = None
windows = {}
currentActive = ''

UPLOAD_DIR = Path("chat_files")
UPLOAD_DIR.mkdir(parents=True, exist_ok=True)

# 设置预览文件的最大大小，单位字节
MAX_FILE_SIZE = 10 * 1024 * 1024  # 10MB

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    # 允许跨域的源列表，例如 ["http://www.example.org"] 等等，["*"] 表示允许任何源
    allow_origins=["*"],
    # 跨域请求是否支持 cookie，默认是 False，如果为 True，allow_origins 必须为具体的源，不可以是 ["*"]
    allow_credentials=False,
    # 允许跨域请求的 HTTP 方法列表，默认是 ["GET"]
    allow_methods=["*"],
    # 允许跨域请求的 HTTP 请求头列表，默认是 []，可以使用 ["*"] 表示允许所有的请求头
    # 当然 Accept、Accept-Language、Content-Language 以及 Content-Type 总之被允许的
    allow_headers=["*"],
)

static_file_abspath = os.path.join(os.path.dirname(__file__), "templates")
app.mount("/assets", StaticFiles(directory=static_file_abspath + '/assets'), name="static")
app.mount("/files", StaticFiles(directory="chat_files"), name="files")


@app.get("/")
def index():
    return FileResponse(f"{static_file_abspath}/index.html")


# 上传文件接口
@app.post("/upload/")
async def upload_file(file: UploadFile = File(...)):
    now_time = str(int(time.time_ns()))
    # 设置文件保存路径
    save_dir = UPLOAD_DIR / now_time
    save_dir.mkdir(parents=True, exist_ok=True)

    # 保存文件
    file_location = save_dir / file.filename

    contents = await file.read()
    with open(file_location, "wb+") as f:
        f.write(contents)

    # 获取文件的大小
    file_size = file_location.stat().st_size

    return JSONResponse({
        "file_name": file.filename,
        "file_size": file_size,
        'type': file.content_type,
        "download_url": now_time + '/' + file.filename
    })


# 启动FastAPI服务
t = threading.Thread(target=uvicorn.run, args=(app,), kwargs={"host": '0.0.0.0', "port": 6986, })
t.daemon = True
t.start()

if __name__ == '__main__':
    # port = assets_proxy_server()
    # url = f'http://127.0.0.1:{port}/#/'

    if getattr(sys, 'frozen', False):
        # port = assets_proxy_server()
        url = f'http://127.0.0.1:6986/#/'
    else:
        url = 'http://localhost:5173/#/'

    session = get_db()
    api = Api(url)
    main_window = webview.create_window('运维工具箱', url, js_api=api, width=410,
                                        height=500)

    windows[main_window.uid] = {'window': main_window}
    setattr(main_window, 'session', session)

    # 监听页面加载完成事件，避免页面打开空白的问题
    main_window.events.loaded += lambda: main_window.show()
    main_window.events.loaded += lambda: api.init()

    webview.settings['OPEN_DEVTOOLS_IN_DEBUG'] = False
    webview.settings['ALLOW_DOWNLOADS'] = True
    webview.start(debug=True, http_port=8777)
